package com.lianyu.wangyiyun.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.RelativeSizeSpan;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.lianyu.wangyiyun.R;
import com.lianyu.wangyiyun.activity.MainActivity;
import com.lianyu.wangyiyun.activity.PlayerActivity;
import com.lianyu.wangyiyun.databinding.MusicItemDialogBinding;
import com.lianyu.wangyiyun.databinding.MusicListDialogBinding;
import com.lianyu.wangyiyun.model.Mp3Info;
import com.lianyu.wangyiyun.model.MusicListViewModel;
import com.lianyu.wangyiyun.service.MusicService;

/**
 * @author Chen Yuguang
 * @date 2021/5/16 22:29
 */
public class MusicDialogFragment extends DialogFragment {

    private MusicListDialogBinding musicListDialogBinding;
    private MusicListViewModel mainMusicListViewModel;
    /**
     * 上一个播放位置
     */
    private int oldPosition = -1;

    private final DiffUtil.ItemCallback<Mp3Info> diffCallback =
            new DiffUtil.ItemCallback<Mp3Info>() {

                @Override
                public boolean areItemsTheSame(@NonNull Mp3Info oldItem, @NonNull Mp3Info newItem) {
                    return oldItem.getId() == newItem.getId();
                }

                @Override
                public boolean areContentsTheSame(@NonNull Mp3Info oldItem, @NonNull Mp3Info newItem) {
                    return oldItem.equals(newItem);
                }
            };

    private final RecyclerAdapter recyclerAdapter = new RecyclerAdapter();

    @SuppressLint("SetTextI18n")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        musicListDialogBinding = MusicListDialogBinding.inflate(inflater, container, false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置布局管理者（竖向的线性布局）
        musicListDialogBinding.musicRecyclerView.setLayoutManager(linearLayoutManager);
        //设置适配器
        musicListDialogBinding.musicRecyclerView.setAdapter(recyclerAdapter);
        TextView nilView = musicListDialogBinding.nilView;
        FragmentActivity fragmentActivity = getActivity();
        if (fragmentActivity != null) {
            //将viewModel与recyclerView的适配器列表绑定在一起
            mainMusicListViewModel = new ViewModelProvider(fragmentActivity, new ViewModelProvider.NewInstanceFactory()).get(MusicListViewModel.class);
            mainMusicListViewModel.getMusicLiveData().observe(this, list -> {
                if (list.size() == 0) {
                    //显示空布局
                    if (nilView.getVisibility() == View.GONE) {
                        nilView.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (nilView.getVisibility() == View.VISIBLE) {
                        nilView.setVisibility(View.GONE);
                    }
                }
                //提交列表给适配器
                recyclerAdapter.submitList(list);
                //显示总曲数
                musicListDialogBinding.totalNum.setText("(" + list.size() + ")");
            });
            //设置模式按钮点击事件
            musicListDialogBinding.mode.setOnClickListener(v -> fragmentActivity.sendBroadcast(new Intent(MainActivity.ACTION_MUSIC_SWITCH)));
        }
        //将mainActivity的ViewModel模式值与模式图和文字绑定在一起
        mainMusicListViewModel.getModeLiveData().observe(this, mode -> {
            switch (mode) {
                case MainActivity.LIST_XUN:
                    //列表循环
                    musicListDialogBinding.modeImage.setImageResource(R.drawable.xlistxun);
                    musicListDialogBinding.modeText.setText("列表循环");
                    break;
                case MainActivity.SUI_XUN:
                    //随机循环
                    musicListDialogBinding.modeImage.setImageResource(R.drawable.xsuiji);
                    musicListDialogBinding.modeText.setText("随机循环");
                    break;
                case MainActivity.ONE_XUN:
                    //单曲循环
                    musicListDialogBinding.modeImage.setImageResource(R.drawable.xonexun);
                    musicListDialogBinding.modeText.setText("单曲循环");
                    break;
                default:
            }
        });
        //获取当前播放位置
        Integer position = mainMusicListViewModel.getPositionLiveData().getValue();
        if (position != null) {
            LinearLayoutManager manager = (LinearLayoutManager) musicListDialogBinding.musicRecyclerView.getLayoutManager();
            if (manager != null) {
                //将当前播放位置-2的item居顶
                int topPosition = position - 2;
                if (topPosition >= 0) {
                    manager.scrollToPositionWithOffset(topPosition, 0);
                } else {
                    manager.scrollToPositionWithOffset(position, 0);
                }
            }
        }
        mainMusicListViewModel.getPositionLiveData().observe(this, newPosition -> {
            //刷新旧的播放位置，取消标红
            if (oldPosition != -1) {
                recyclerAdapter.notifyItemChanged(oldPosition);
            }
            //刷新新的播放位置，标红
            recyclerAdapter.notifyItemChanged(newPosition);
            //替换旧的播放位置为新的
            oldPosition = newPosition;
        });
        return musicListDialogBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Dialog dialog = getDialog();
        if (dialog != null) {
            Window dialogWindow = dialog.getWindow();
            //设置dialog显示靠底
            dialogWindow.setGravity(Gravity.BOTTOM);
            //设置动画效果
            dialogWindow.setWindowAnimations(R.style.AnimBottom);
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            //设置dialog宽高
            Context context = getContext();
            if (context != null) {
                DisplayMetrics metrics = context.getResources().getDisplayMetrics();
                int width = metrics.widthPixels;
                int height = metrics.heightPixels;
                lp.width = width * 9 / 10;
                lp.height = height * 3 / 5;
                lp.y = height / 40;
                dialogWindow.setAttributes(lp);
                //设置dialog背景
                dialogWindow.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.radius_drawable_bg_dialog));
            }
            //点击外部Dialog消失
            dialog.setCanceledOnTouchOutside(true);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private class RecyclerAdapter extends ListAdapter<Mp3Info, RecyclerAdapter.ViewHolder> {

        protected RecyclerAdapter() {
            super(diffCallback);
        }

        //创建视图
        @Override
        public @NonNull
        RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            MusicItemDialogBinding musicItemDialogBinding = MusicItemDialogBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
            return new RecyclerAdapter.ViewHolder(musicItemDialogBinding);
        }

        //数据绑定
        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull RecyclerAdapter.ViewHolder holder, int position) {
            String title = getCurrentList().get(position).getTitle();
            String artist = getCurrentList().get(position).getArtist();
            SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
            SpannableString spannableString = new SpannableString(" - " + artist);
            //设置大小
            RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(0.75f);
            Context context = getContext();
            int color;
            Integer nowPosition = mainMusicListViewModel.getPositionLiveData().getValue();
            if (nowPosition != null && position == nowPosition) {
                //设置图片
                ImageSpan imageSpan = new ImageSpan(context, R.drawable.playing);
                spannableStringBuilder.append("♪ ");
                spannableStringBuilder.setSpan(imageSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                color = Color.RED;
                holder.title.setTextColor(color);
            } else {
                color = Color.GRAY;
                holder.title.setTextColor(Color.BLACK);
            }
            //设置颜色
            ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(color);
            //给歌手文本设置颜色和大小
            spannableString.setSpan(relativeSizeSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(foregroundColorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableStringBuilder.append(title);
            spannableStringBuilder.append(spannableString);
            holder.title.setText(spannableStringBuilder);
            holder.itemView.setOnClickListener(v -> {
                //playerActivity与MainActivity同步当前播放值
                if (getActivity() instanceof PlayerActivity) {
                    Intent broadcastIntent = new Intent(MainActivity.ACTION_MUSIC_MAIN_POSITION);
                    broadcastIntent.putExtra("position", position);
                    if (context != null) {
                        context.sendBroadcast(broadcastIntent);
                    }
                    return;
                }
                //设置要传给mainActivity的viewModel值（播放的位置）
                mainMusicListViewModel.getPositionLiveData().setValue(position);
                Intent serviceIntent = new Intent(context, MusicService.class);
                Mp3Info mp3Info = getCurrentList().get(position);
                //传送url给service播放
                serviceIntent.putExtra("url", mp3Info.getUrl());
                serviceIntent.putExtra("title", mp3Info.getTitle());
                serviceIntent.putExtra("artist", mp3Info.getArtist());
                if (context != null) {
                    context.startService(serviceIntent);
                }
            });
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            public TextView title;

            public ViewHolder(@NonNull MusicItemDialogBinding musicItemDialogBinding) {
                super(musicItemDialogBinding.getRoot());
                title = musicItemDialogBinding.title;
            }
        }

    }
}
